<template>
  <div
    class="source"
    v-loading="pageLoading"
    element-loading-text="loading"
  >
    <div class="newPageTitle">
      <span class="backIcon" @click="closeDrawer">
        <i class="el-icon-back"></i>
      </span>
      <h1 style="display: inline-block; margin-left: 10px">{{ pageTitle }}</h1>
    </div>
    <el-form
      :model="editData"
      :rules="rules"
      ref="editRole"
      label-width="110px"
      label-position="top"
      size="small"
      class="updateForm"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="editData.roleName"
          placeholder="角色名称"
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item label="角色编号" prop="bocRoleId">
        <el-input
          v-model="editData.bocRoleId"
          placeholder="角色编号"
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item prop="menu2bids">
        <span slot="label">
          <span style="color: #f56c6c">*&nbsp;</span>
          {{ authName }}
        </span>
        <el-checkbox
          class="select-all"
          label="全选"
          v-model="selectAll"
          @change="selectAllChange"
        ></el-checkbox>
        <custome-tree
          :data="allRoleData"
          show-checkbox
          default-expand-all
          :default-checked-keys="editData.menu2bids"
          node-key="id"
          ref="tree"
          :indent="30"
          highlight-current
          @check-change="handleCheckChange"
          :props="defaultProps"
        >
          <span class="custom-tree-node" slot-scope="{ node }">
            <span>{{ getNodeLabel(node) }}</span>
          </span>
        </custome-tree>
      </el-form-item>
    </el-form>
    <div class="footer">
      <div class="footer-btn">
        <el-button @click="closeDrawer" class="reset-btn">
          取消
        </el-button>
        <el-button @click="saveEdit('editRole')" class="search-btn">
          确定
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
// import { searchSingleRole, editRoleSave, addRoleSave } from '@/api/role'
import { editRoleSave, searchSingleRole, getAllRole } from '@/api/role'
import CustomeTree from '@/components/CustomeTree/tree'
import { setRouterParams, getRouterParams } from '@/utils/auth'
export default {
  name: 'UpdateRole',

  components: {
    CustomeTree
  },

  data () {
    return {
      selectAll: false,
      roleAuth: false,
      dataAuth: false,
      pageLoading: false,
      editData: {},
      allRoleData: [],
      rules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          }
        ],
        bocRoleId: [
          {
            required: true,
            message: '请输入角色Code',
            trigger: 'blur'
          }
        ]
      },
      defaultProps: {
        id: 'id',
        children: 'children',
        label: function (data, node) {
          return data.text
        }
      },
      isUpdate: false,
      treeChangeData: []
    }
  },

  computed: {
    pageTitle () {
      if (this.roleAuth) {
        return '编辑权限'
      }
      return '编辑数据'
    },
    authName () {
      if (this.roleAuth) {
        return '角色权限'
      }
      return '数据权限'
    },

    authStr () {
      return this.$route.params.id ? 'system:role:edit:updatebtn' : 'system:role:add:updatebtn'
    }
  },

  // 监听editData的数据变化
  watch: {
    editData: {
      handler () {
        this.isUpdate = true
      },
      deep: true
    }
  },

  mounted () {
    // this.pageLoading = true
    const id = this.$route.params.id
    if (id) {
      this.roleAuth = id.roleAuth
      this.dataAuth = id.dataAuth
      this.isUpdate = false
      setRouterParams(this.$route)
      if (this.roleAuth) {
        this.getAllRole()
        this.editAction(id.id)
      }
    } else {
      const routeParams = getRouterParams(this.$route)
      this.roleAuth = routeParams.id.roleAuth
      this.dataAuth = routeParams.id.dataAuth
      if (this.roleAuth) {
        this.getAllRole()
        this.editAction(routeParams.id.id)
      }
    }
  },

  methods: {
    selectAllChange (val) {
      if (val) {
        this.$refs.tree.setCheckedNodes(this.allRoleData)
      } else {
        this.$refs.tree.setCheckedNodes([])
      }
    },
    getNodeLabel (node) {
      if (node && node.data.text === 'list') return 'view'
      return node.label
    },
    // 查询菜单权限树
    getAllRole () {
      getAllRole().then(response => {
        // 调用接口保存新增修改attribute
        const data = response
        if (data) {
          if (Number(data.code) === 1) {
            this.allRoleData = data.obj
            // 向子组件传递组织语言、以编辑的语言内容、语言value的key值
          } else {
            this.$confirm(this.$t(data.code), {
              confirmButtonText: '确定',
              showCancelButton: false
            })
          }
        }
      })
    },
    // 初始化add页面数据
    initpage () {
      this.pageLoading = true
      // 初始页面值
      this.editData = {
        id: null,
        roleName: '',
        menu2bids: []
      }
      // 向子组件传递组织语言、以编辑的语言内容（新增是传''即可）、语言value的key值
      this.pageLoading = false
    },
    // 修改tree
    handleCheckChange (data, checked, indeterminate) {
      this.isUpdate = true
      if (checked === true) {
        this.selectAll = true
      } else {
        this.selectAll = false
      }
    },

    // 编辑操作
    editAction (id) {
      searchSingleRole(id).then(response => {
        // 调用接口保存新增修改attribute
        const data = response
        if (data) {
          if (Number(data.code) === 1) {
            this.editData = data.obj
            const selectNode = []
            data.obj.menus.forEach(item => {
              // 只接受 type 为 2(按钮类型的去选中)
              if (Number(item.menuType) === 2) {
                selectNode.push(item.id)
                this.selectAll = true
              }
            })
            this.editData.menu2bids = selectNode
            this.pageLoading = false
          } else {
            this.$confirm(this.$t(data.result.code), {
              confirmButtonText: '确定',
              showCancelButton: false
            })
          }
          // 获取首屏数据，将监听器关闭
          this.$nextTick(() => {
            this.isUpdate = false
          })
        }
      })
    },

    // 保存数据操作
    saveEdit () {
      this.$refs.editRole.validate(async valid => {
        if (valid) {
          this.pageLoading = true
          this.editData.menuIds = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
          if (this.editData.menuIds.length <= 0) {
            this.$alert('请至少选择一项')
            this.pageLoading = false
            return false
          }
          editRoleSave(this.editData).then(response => {
            // 调用接口保存新增修改attribute
            const data = response
            if (data) {
              if (Number(data.code) === 1) {
                this.$confirm('操作成功', '', {
                  confirmButtonText: '确定',
                  showCancelButton: false
                }).then(() => {
                  this.$router.push({
                    name: 'roleList'
                  })
                })
              } else {
                this.$confirm(this.$t(data.messageCode), {
                  confirmButtonText: 'OK',
                  showCancelButton: false
                })
              }
              this.pageLoading = false
            }
          })
            .catch(() => {
              this.$confirm('submit error', {
                confirmButtonText: 'OK',
                showCancelButton: false
              })
            })
        }
      })
    },

    // 关闭页面操作（cancel）
    closeDrawer () {
      if (this.isUpdate) {
        this.$confirm('确定离开此页面？如果离开，更改将丢失', '', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        })
          .then(() => {
            this.$router.push({ name: 'roleList' })
          })
          .catch(() => { })
      } else {
        this.$router.push({ name: 'roleList' })
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
 /deep/ .el-checkbox__label {
  font-size: 1.3rem !important
}
.cateBox {
  display: inline-block;
  border: 1px solid #979797;
  padding: 5px 10px;
  min-width: 40%;
  .el-tag {
    margin-right: 10px;
  }
}
</style>
